<?php

namespace App\Http\Controllers\Backend;


use App\Models\ArticleComment;
use App\Models\Event;
use App\Models\EventCate;
use App\Models\EventComment;
use App\Models\Need;
use App\Models\User;

class EventController extends BaseController
{
    protected $list_cache = true;

    // 快讯
    public function initialize()
    {
        parent::initialize();

        $this->model = 'Event';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 返回列表数据
    public function lists()
    {
        $where = $this->listWhere();
        $page  = $this->page;
        $rows  = $this->rows;
        $model = new Event();

        // 模型 和 查询
        if(empty($this->list_cache)){
            $result = $model->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->isCache(true)->listPage($where, $page, $rows, "id DESC");
        }
        // 数据整理
        if($result['list']){
            $cateDb = new EventCate();
            $userDb = new User();
            $cids   = array_column($result['list'], 'cate_id');
            $uids   = array_column($result['list'], 'uid');
            $cates  = $cateDb->isCache(true)->getListInIds($cids);
            $users  = $userDb->isCache(true)->getListInIds($uids);
            $users  = array_column($users, null, 'id');
            $types  = $this->userType(); // 认证类型
            foreach($result['list'] as $key => $item){
                $_cid  = $item['cate_id'];
                $_uid  = $item['uid'];
                $_user = $users[$_uid] ?? [];
                $_cate = $cates[$_cid] ?? [];

                // 整理
                if($_user){
                    $_user['apply_type'] = $_user['is_apply'] == 1 ? ($types[$_user['apply_type']]['name'] ?? '') : '';
                    $_user['head_img']   = $this->getHeadImg($_user['head_img'] ?? '');
                } else{
                    $_user = (object)[];
                }

                // 状态 开始，结束，正在进行
                $is_status = $item['start_time'] > LARAVEL_TIME ? '未开始' : ($item['end_time'] < LARAVEL_TIME ? '已结束' : '进行中');
                // 整理
                $result['list'][$key]['content']   = $this->makeListShow($item['content']);
                $result['list'][$key]['user']      = $_user;
                $result['list'][$key]['cover']     = $this->getFullUrl($item['cover']);
                $result['list'][$key]['is_status'] = $is_status;
                $result['list'][$key]['cate']      = $_cate;
            }
        }

        return $this->success($result);
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = new Event();
        $result = $model->isCache(true)->softDelete($where);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 查找
    public function show()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');

        $where = [['id', '=', $this->id],]; // ['verify', '=', 1]
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());
        $this->throwIf(empty($info), '你要查看的活动不存在！');

        // 数据整理
        $info['cover']  = $this->getFullUrl($info['cover']);
        $info['images'] = $info['images'] ? json_decode($info['images'], true) : [];
        // 查找用户信息
        if($info['uid']){
            $cid    = $info['cate_id'];
            $uid    = $info['uid'];
            $userDb = new User();
            $cateDb = new EventCate();
            $types  = $this->userType(); // 认证类型
            // $user   = $userDb->isCache(true)->getListInIds([$uid]);
            $user = $userDb->isCache(true)->getOneById($uid);
            $cate = $cateDb->isCache(true)->getOneById($cid);
            if($user){
                // $user               = $user[$uid];
                // 整理
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
            }
            $info['user'] = $user;
            $info['cate'] = $cate;
        }

        return $this->success($info);
    }

    // 启用禁用
    public function verify()
    {
        $_value = $this->getData('verify', 0, 'intval');
        $this->throwIf(is_null($_value), '审核状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1, 2]), '审核状态必须为2或1！');

        return $this->changeField('verify', $_value);
    }

    // 删除（软删除）
    public function delComment()
    {
        $ids = $this->getData('ids', [], 'is_array');
        $this->throwIf(empty($ids), '请指定删除记录!');
        $this->throwIf(count($ids) != count($ids, 1), '指定删除记录参数错误!');
        // 其他条件
        $event_id = $this->getData('event_id', 0, 'intval');
        $this->throwIf(empty($need_id), '请指定需求编号!');

        //$where   = ['event_id' => $event_id];
        //$comment = new EventComment();

        $where   = ['channel' => 'event', 'article_id' => $event_id];
        $comment = new ArticleComment();

        $result = $comment->isCache(true)->softDelete($where, $ids);
        $this->throwIf($result === false, $comment->getError());

        return $this->success();
    }

    // 快讯的评论
    public function comment()
    {
        $event_id = $this->getData('event_id', 0, 'intval');
        $this->throwIf(empty($event_id), '请指定查看记录');
        $where   = ['article_id' => $event_id, 'channel' => 'event', 'verify' => 1]; // 'pid' => 0,
        $comment = new ArticleComment();

        //$where   = ['event_id' => $event_id, 'verify' => 1]; // 'pid' => 0,
        //$comment = new EventComment();

        $result = $comment->listPage($where, $this->page, $this->rows);
        if($result['list']){
            $uids   = array_column($result['list'], 'uid');
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($result['list'] as $key => $item){
                $_uid  = $item['uid'];
                $_info = $users[$_uid] ?? [];
                if($_info){
                    $_info['head_img']   = $this->getHeadImg($_info['head_img'] ?? '');
                    $_info['apply_type'] = $_info['is_apply'] == 1 ? ($types[$_info['apply_type']]['name'] ?? '') : '';
                }

                // 整理
                $result['list'][$key]['user'] = $_info;
            }
        }

        return $this->success($result);
    }

    // 发活动
    public function publish()
    {
        $images   = $this->getData('images', [], 'is_array');
        $is_draft = $this->getData('is_draft', 0, 'intval');
        $uid      = $this->getData('uid', 0, 'intval');
        $title    = $this->getData('title', '', 'trim');
        $content  = $this->getData('content', '', 'trim');
        $this->throwIf(empty($content), '请填写转发内容!');
        $this->throwIf(empty($uid), '请选择发布的用户!');
        //$this->throwIf(empty($title), '请填写需求标题!');

        // 发送消息的频率
        //$freshDb = new Need();
        //$where   = [["uid", '=', $this->myUid], ["ctime", '>', LARAVEL_TIME - 60 * 60]];
        //$nums    = $freshDb->where($where)->count();
        //$this->throwIf($nums >= 3, '你发送消息太频繁，请休息下再来！!');

        // 审核转发内容
        //$spam = antispam($content);
        //$this->throwIf(empty($spam), '含有不符合内容!!');

        $start_time = $this->getData("start_time", 0, 'intval');
        $end_time   = $this->getData("end_time", 0, 'intval');
        $address    = $this->getData("address", null, 'trim');
        $cover      = $this->getData("cover", null, 'trim');
        $this->throwReturn($end_time <= $start_time, '结束时间不能小于开始时间！');
        $this->throwReturn(empty($address), '活动，请指定参加地址！');

        // TODO 提取图片
        if(empty($images)){
            $images = $this->getImage4content($content);
        }
        $this->throwIf(count($images) != count($images, 1), '请传递正确图片地址！');
        if(empty($cover) && $images){
            $cover = $images[0];
        }

        // 数据
        $ip   = $this->request->ip();
        $data = [
            'uid'        => $uid,
            'content'    => $content,
            'images'     => json_encode($images),
            'title'      => $title,
            'is_draft'   => $is_draft,
            'ip'         => $ip,
            'ip_address' => $this->getIpAddress($ip),
            'verify'     => 1,
            'cate_id'    => $this->getData("cate_id", 0, 'intval'),
            //'pic'        => $this->getData("pic"),
            //'itype'      => $this->getData("itype"),
            //'number'     => $this->getData("number"),


            'cover'      => $cover,
            'start_time' => $start_time,
            'end_time'   => $end_time,
            'is_online'  => $this->getData("is_online", 0, 'intval'),
            'address'    => $address,

            'address_name' => $this->getData("address_name", null, 'trim'),
            'latitude'     => $this->getData("latitude", 0, 'trim'),
            'longitude'    => $this->getData("longitude", 0, 'trim'),
            'number'       => $this->getData("number", 0, 'intval'),
            'power'        => $this->getData("power", 'all', 'trim'),
        ];

        // TODO 审核
        $this->baiduTextCensor($title.$content);

        // 执行发布
        $freshDb = new Need();
        $id      = $freshDb->publish($uid, $data);
        $this->throwIf($id === false, $freshDb->getError());
        // 获取金币
        if(empty($is_draft)){
            // $this->addGold('fresh_long', $uid);
        }

        return $this->success($id);
    }

    // 添加（为了调用 event模型的publish方法）
    public function add()
    {
        $uid  = $this->getData('uid', 0, 'intval');
        $data = $this->_before_add();
        $this->throwIf($data === false, $this->error);

        // 组合数据
        $data  = $this->filterNull($data);
        $model = $this->checkModel($this->model);
        $data  = $model->checkData($data);
        $this->throwIf($data === false, $model->getError());

        // 验证
        $result = $model->checkRules($data, 'add');
        $this->throwIf($result === false, $model->getError());

        // 保存
        $id = $model->publish($uid, $data);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表查询
    protected function listWhere()
    {
        $keyword = $this->getData('keyword', null, 'trim');
        $cate_id = $this->getData('cate_id', null, 'intval');
        $uid     = $this->getData('uid', null, 'intval');
        $isLine  = $this->getData('is_online', 1, 'intval');
        $verify  = $this->getData('verify', null, 'intval');
        $where   = [];  //  ['is_online', '=', $isLine]
        if($keyword){
            $where[] = $this->orWhere('title|content', 'like', $keyword);
            // 不在缓存
            $this->list_cache = false;
        }
        if(is_null($verify)){
            $where[] = ['verify', '>=', 0];
        }else{
            $where[] = ['verify', '=', $verify];
        }


        // 时间筛选
        $startTime = $this->getData('start_time', 0, 'intval');
        $endTime   = $this->getData('end_time', 0, 'intval');
        if($startTime){
            $where[] = ['start_time', '>=', $startTime];
        }
        if($endTime){
            $where[] = ['start_time', '<=', $endTime];
        }
        if($uid){
            $where[] = ['uid', '=', $uid];
        }
        if($cate_id){
            $where[] = ['cate_id', '=', $cate_id];
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $images = $this->getData('images', [], 'is_array');
        $ip     = $this->request->ip();
        $data   = [
            // 'id'          => $this->getData("id"),
            'uid'          => $this->getData("uid", 0, 'trim'),
            'cate_id'      => $this->getData("cate_id", 0, 'trim'),
            'title'        => $this->getData("title", null, 'trim'),
            'cover'        => $this->getData("cover", null, 'trim'),
            'content'      => $this->getData("content", null, 'trim'),
            'start_time'   => $this->getData("start_time", 0, 'intval'),
            'end_time'     => $this->getData("end_time", 0, 'intval'),
            'is_online'    => $this->getData("is_online", 0, 'intval'),
            'address'      => $this->getData("address", null, 'trim'),
            'address_name' => $this->getData("address_name", null, 'trim'),
            'latitude'     => $this->getData("latitude", 0, 'trim'),
            'longitude'    => $this->getData("longitude", 0, 'trim'),
            'number'       => $this->getData("number", 0, 'intval'),
            'power'        => $this->getData("power", 'all', 'trim'),
            'verify'       => 1,
            // 'is_over'     => $this->getData("is_over", 0, 'intval'),
            // 'ctime'       => $this->getData("ctime", 0, 'intval'),
            // 'mtime'       => $this->getData("mtime", 0, 'intval'),
            'ip_address'   => $this->getIpAddress($ip),
            'ip'           => $ip,
        ];

        // 线下活动
        $this->throwReturn($data['end_time'] <= $data['start_time'], '结束时间不能小于开始时间！');
        $this->throwReturn(empty($data['address']), '活动，请指定参加地址！');
        //$this->throwReturn(empty($data['latitude']), '活动，请指定纬度！');
        //$this->throwReturn(empty($data['longitude']), '活动，请指定经度！');
        if(empty($images)){
            $images = $this->getImage4content($data['content']);
        }
        $this->throwIf(count($images) != count($images, 1), '请传递正确图片地址！');
        if(empty($data['cover']) && $images){
            $data['cover'] = $images[0];
        }

        // TODO 审核
        $data['images'] = json_encode($images);
        $this->baiduTextCensor($data['title'].$data['content']);

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $images = $this->getData('images', [], 'is_array');
        $data   = [
            'uid'          => $this->getData("uid", 0, 'trim'),
            'cate_id'      => $this->getData("cate_id", 0, 'trim'),
            'title'        => $this->getData("title", null, 'trim'),
            'cover'        => $this->getData("cover", null, 'trim'),
            'content'      => $this->getData("content", null, 'trim'),
            'start_time'   => $this->getData("start_time", 0, 'intval'),
            'end_time'     => $this->getData("end_time", 0, 'intval'),
            'is_online'    => $this->getData("is_online", 0, 'intval'),
            'address'      => $this->getData("address", null, 'trim'),
            'address_name' => $this->getData("address_name", null, 'trim'),
            'latitude'     => $this->getData("latitude", 0, 'trim'),
            'longitude'    => $this->getData("longitude", 0, 'trim'),
            'number'       => $this->getData("number", 0, 'intval'),
            'power'        => $this->getData("power", 'all', 'trim'),
            'verify'       => 1,
        ];

        // 线下活动
        $this->throwReturn($data['end_time'] <= $data['start_time'], '结束时间不能小于开始时间！');
        $this->throwReturn(empty($data['address']), '活动，请指定参加地址！');
        //$this->throwReturn(empty($data['latitude']), '活动，请指定纬度！');
        //$this->throwReturn(empty($data['longitude']), '活动，请指定经度！');

        if(empty($images)){
            $images = $this->getImage4content($data['content']);
        }
        $this->throwIf(count($images) != count($images, 1), '请传递正确图片地址！');

        // TODO 审核
        $data['images'] = json_encode($images);
        $this->baiduTextCensor($data);

        return $data;
    }

}


